package com.example.performance.jol.official;

import org.openjdk.jol.vm.VM;

import java.io.PrintWriter;

/**
 * @author Aleksey Shipilev
 */
@SuppressWarnings({"java:S101", "java:S106"})
public class JOLSample_20_Allocation {

    /*
     * The example of allocation addresses.
     *
     * This example shows the addresses of newly allocated objects
     * grow linearly in HotSpot.
     * This is because the allocation in parallel collectors is linear.
     * We can also see it rewinds back to the same offsets --
     * that's the start of some GC generation.
     *
     * For Parallel-like GCs, while GC adjusts for the allocation rate.
     * For G1-like GCs, the allocation address changes by region size,
     * as collector switches to another region for allocation.
     *
     * Run with test with smaller heap (about 1 GB) for best results.
     */

    public static void main(String[] args) {
        System.out.println(VM.current().details());

        PrintWriter pw = new PrintWriter(System.out, true);

        long last = VM.current().addressOf(new Object());
        for (int l = 0; l < 1000 * 1000 * 100; l++) {
            long current = VM.current().addressOf(new Object());

            long distance = Math.abs(current - last);
            if (distance > 4096) {
                pw.printf("Jumping from %x to %x (distance = %d bytes, %dK, %dM)%n",
                        last,
                        current,
                        distance,
                        distance / 1024,
                        distance / 1024 / 1024);
            }

            last = current;
        }

        pw.close();
    }

}
